import { Snowflake } from "api/structures/utils/Snowflake";

interface DMListModel {
    id: string
    userName: string
    userAvatar: string
    subText: string
}

declare const listModel: Qml.ListModel<DMListModel>;

export function handleReady() {

    console.log("DMMesaagesPage.handleReady")

    window.client.on("ready", handleClientReady)
    window.client.on("disconnect", () => {
        listModel.clear()
    })
}

function handleDestroy() {

    console.log("DMMesaagesPage.handleDestroy")

    window.client.off("ready", handleClientReady)
}

function showDMChat(id: string) {
    window.client.emit("debug", "Show db chat " + id)
    window.pageStack.push("./BasicChat.qml", { chat_id: id }) as Qml.Page;
}

function showGuildChat(id: string) {
    window.client.emit("debug", "Show db chat " + id)
    window.pageStack.push("./BasicChat.qml", { chat_id: id }) as Qml.Page;
}

function handleClientReady() {

    listModel.clear()
    
    try {

        window.client.emit("debug", "start dms")

        const dms: DMListModel[] = Object.keys(window.client.privateChannels)
        .map(id => {
            return window.client.privateChannels[id]
        })
        .filter((c) => c.last_message_id !== null)
        .sort((a, b) => {
            const snA = Snowflake.deconstruct(a.last_message_id);
            const snB = Snowflake.deconstruct(b.last_message_id);

            return snB.timestamp - snA.timestamp;
        }).map((channel, index, arr) => {

            // window.client.emit("debug", "start pushing data " + index + "/" + arr.length)

            //https://discord.com/assets/641edf794e368d5e8180.png
            
            try {
                
                if (channel.type == 3) {

                    let name: string[] = []

                    for (let index = 0; index < channel.recipients.length; index++) {
                        if (channel.recipients[index]) {
                            name.push(channel.recipients[index].global_name)
                        } else {
                            name.push("recipient(" + index + ")")
                        }
                    }

                    // window.client.emit("debug", "name size " + name.length)

                    return {
                        id: channel.id,
                        userAvatar: "https://discord.com/assets/641edf794e368d5e8180.png",
                        userName: name.join(", "),
                        subText: name.length + " участника"
                    }
                } else {

                    // window.client.emit("debug", "name " + channel.recipients[0].global_name)

                    return {
                        id: channel.id,
                        userAvatar: channel.recipients[0].avatarURL,
                        userName: channel.recipients[0].global_name,
                        subText: ""
                    }
                }
            } catch(err: any) {
                window.client.emit("debug", "2: Error " + err.message + ", " + err.stack)
                return {
                    id: channel.id,
                    userAvatar: "",
                    userName: "Error " + channel.id,
                    subText: ""
                }
            }
        });

        window.client.emit("debug", "ended dms.size " + dms.length)

        dms.forEach((dm, index) => {
            // window.client.emit("debug", "listModel.append " + index + "/" + dms.length)
            listModel.append(dm)
        });
    } catch(err: any) {
        window.client.emit("debug", "2: Error " + JSON.stringify(err) + ", " + err.message + ", " + err.stack)
    }
}